package com.huanying.goodjob.message;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;
import com.huanying.framework.BaseController;
import com.huanying.framework.PageBean;
import com.huanying.framework.user.User;
import com.huanying.framework.user.UserService;
import com.huanying.goodjob.job.Job;
import com.huanying.goodjob.job.JobService;
import com.huanying.goodjob.job.Jobitem;
import com.huanying.goodjob.job.Jobitem_User;

@Controller
public class MessageController extends BaseController{
	@Autowired
	private UserService userService;
	@Autowired
	private JobService jobService;
	@Autowired
	private MessageService messageService;
	private static Logger logger = Logger.getLogger(MessageController.class);
//查询消息
	@RequestMapping("/show_add_message.do")
	public String show_add_message(String sender, String receiver, String page_num, String issystemmessage,
			Model model) {
		Map<String, Object> map = new HashMap<String, Object>();
		PageBean pageBean = null;
		map.put("sender", sender);
		map.put("receiver", receiver);
		if (page_num == null) {
			page_num = "1";
		}

		try {
			pageBean = messageService.search_message(map, super.getPageSize(), Integer.valueOf(page_num));
		} catch (NumberFormatException e) {
			logger.error("查询消息失败", e);
			// TODO Auto-generated catch block
		} catch (Exception e) {
			logger.error("查询消息失败", e);
			// TODO Auto-generated catch block
		}
		model.addAttribute("sender", sender);
		model.addAttribute("receiver", receiver);
		model.addAttribute("systemstatus", issystemmessage);
		model.addAttribute("messages", pageBean.getList());
		model.addAttribute("page", pageBean);

		return "/message/add_message";
	}
//获得单个消息
	@RequestMapping(value = "/get_message.do", method = RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> get_message(int id) {
		Map<String, Object> map = new HashMap<String, Object>();
		Message message;
		try {
			message = messageService.get_message(id);
			map.put("message", message);
		} catch (Exception e) {
			logger.error("获取消息失败", e);
			// TODO Auto-generated catch block
		}
		return map;
	}
//删除消息
	@RequestMapping(value = "/delete_message.do", method = RequestMethod.GET)
	@ResponseBody
	public Map<String, String> delete_message(int id) {
		Map<String, String> map = new HashMap<String, String>();
		try {
			messageService.delete_message(id);
			map.put("flag", "1");
		} catch (Exception e) {
			logger.error("删除消息失败", e);
			// TODO Auto-generated catch block
			map.put("flag", "0");
		}
		return map;
	}
//更新消息
	@RequestMapping(value = "/update_message.do", method = RequestMethod.GET)
	@ResponseBody
	public Map<String, String> update_message(int id, int status) {
		Map<String, String> map = new HashMap<String, String>();
		try {
			messageService.update_message(id, status);
			map.put("flag", "1");
			map.put("id", Integer.toString(id));
		} catch (Exception e) {
			logger.error("修改消息失败", e);
			// TODO Auto-generated catch block
			map.put("flag", "0");
		}
		return map;
	}

	// 前台获取消息
	@RequestMapping(value = "/front_get_messages.do", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
	@ResponseBody
	public String front_get_messages(String jsoncallback, String user_id) {
		Map<String, Object> map = new HashMap<String, Object>();
		List list = new ArrayList();
		try {
			list = messageService.front_get_message(Integer.parseInt(user_id));
			map.put("list", list);
		} catch (Exception e) {
			logger.error("前台发送消息失败", e);
			// TODO Auto-generated catch block
		}
		Gson gson = new Gson();
		String str = gson.toJson(map);
		return jsoncallback + "(" + str + ")";
	}

	// 添加工长发起开工请求的消息
	@RequestMapping(value = "/add_message.do", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
	@ResponseBody
	public String add_message(String user_id, String jobitem_id, int flag, String jsoncallback) {
		Message messages = new Message();
		Map<String, Object> map = new HashMap<String, Object>();
		Jobitem_User jobitem_user;
		Jobitem jobitem;
		User reciver;
		User sender;
		Job job;
		List<Jobitem_User> jobitem_users;
		try {
			sender = userService.getbyId(Integer.parseInt(user_id));
			messages.setSender(sender);
			messages.setStatus(1);
			messages.setIssystemmessage(1);
			messages.setCheckstatus(0);
			if (flag == 1 || flag == 2) {
				jobitem_users = jobService.getbyjobitem_id_jobitem_user(Integer.parseInt(jobitem_id));
				for (int i = 0; i < jobitem_users.size(); i++) {
					jobitem_user = jobitem_users.get(i);
					reciver = userService.getbyId(jobitem_user.getUser().getId());
					jobitem = jobService.getbyId_jobitem(Integer.parseInt(jobitem_id));
					if (flag == 1) // 工长确认用工
					{
						if (jobitem_user.getJobitem_status() == 1) {
							messages.setReceiver(reciver);
							messages.setJobitem(jobitem);
							messages.setMessage("恭喜您被工长选中了");
                            messages.setReceiver_type(0);
						} else if (jobitem_user.getJobitem_status() == 2){
							messages.setReceiver(reciver);
							messages.setJobitem(jobitem);
							messages.setMessage("很遗憾你没有被工长选中");
							messages.setReceiver_type(0);
						}
						messageService.add_message(messages);
					}
					if (flag == 2) // 请求开工
					{
						if (jobitem_user.getJobitem_status() == 1) {
							messages.setReceiver(reciver);
							messages.setJobitem(jobitem);
							messages.setMessage("工长发出开工请求，请及时点击确认");
							messages.setReceiver_type(0);
							messageService.add_message(messages);
						}
						
					}
				}
			}
			if (flag == 3) // 工人确认开工
			{
				jobitem = jobService.getbyId_jobitem(Integer.parseInt(jobitem_id));
				job = jobitem.getJob();
				reciver = job.getUser();
				messages.setReceiver(reciver);
				messages.setJobitem(jobitem);
				messages.setMessage("工人已确认开工");
				messages.setReceiver_type(1);
				messageService.add_message(messages);
			}
			if (flag == 4) // 工人请求完工
			{
				jobitem = jobService.getbyId_jobitem(Integer.parseInt(jobitem_id));
				job = jobitem.getJob();
				reciver = job.getUser();
				messages.setReceiver(reciver);
				messages.setJobitem(jobitem);
				messages.setMessage("工人发起完工请求");
				messages.setReceiver_type(1);
				messageService.add_message(messages);
			}
			if (flag == 5) // 工长请求返工
			{
				jobitem_users = jobService.getbyjobitem_id_jobitem_user(Integer.parseInt(jobitem_id));
				for (int i = 0; i < jobitem_users.size(); i++) {
					jobitem_user = jobitem_users.get(i);
					reciver = userService.getbyId(jobitem_user.getUser().getId());
					jobitem = jobService.getbyId_jobitem(Integer.parseInt(jobitem_id));
					if (jobitem_user.getJobitem_status()== 1) {
						messages.setReceiver(reciver);
						messages.setJobitem(jobitem);
						messages.setMessage("工长请求返工");
						messages.setReceiver_type(0);
						messageService.add_message(messages);
					}

				}
			}
			if (flag == 6) // 工长确认完工
			{
				jobitem_users = jobService.getbyjobitem_id_jobitem_user(Integer.parseInt(jobitem_id));
				for (int i = 0; i < jobitem_users.size(); i++) {
					jobitem_user = jobitem_users.get(i);
					reciver = userService.getbyId(jobitem_user.getUser().getId());
					jobitem = jobService.getbyId_jobitem(Integer.parseInt(jobitem_id));
					if (jobitem_user.getJobitem_status() == 1) {
						messages.setReceiver(reciver);
						messages.setJobitem(jobitem);
						messages.setMessage("工长已确认完工");
						messages.setReceiver_type(0);
						messageService.add_message(messages);
					}

				}
			}
		} catch (NumberFormatException e) {
			logger.error("添加消息失败", e);
			// TODO Auto-generated catch block

		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error("添加消息失败", e);

		}
		Gson gson = new Gson();
		String str = gson.toJson(map);
		return jsoncallback + "(" + str + ")";

	}
	// 前台删除消息
	@RequestMapping(value="/front_delete_message.do", method = RequestMethod.GET,produces = "application/json; charset=utf-8")
	@ResponseBody 
	public String  front_delete_message(String id,String jsoncallback) {
		Map<String, String> map = new HashMap<String, String>();
		try {		
			messageService.delete_message(Integer.valueOf(id));
			map.put("flag", "1");
		} catch (Exception e) {
			logger.error("前台删除消息失败", e);
			// TODO Auto-generated catch block
			map.put("flag", "0");
		}
		Gson gson=new Gson();
		String str=gson.toJson(map);
		return jsoncallback+"("+str+")";
	}

	// 前台清空消息
		@RequestMapping(value = "/front_delete_allmessage.do", method = RequestMethod.GET,produces = "application/json; charset=utf-8")
		@ResponseBody
		public String front_delete_allmessage(String jsoncallback, String reciveuser_id) {
			Map<String, String> map = new HashMap<String, String>();
			try {
				messageService.delete_allmessage(Integer.valueOf(reciveuser_id));
				map.put("flag", "1");
			} catch (Exception e) {
				logger.error("前台删除消息失败", e);
				// TODO Auto-generated catch block
				map.put("flag", "0");
			}
			Gson gson = new Gson();
			String str = gson.toJson(map);
			return jsoncallback + "(" + str + ")";
		}

	
	// 前台获取具体的某个消息
	@RequestMapping(value = "/front_get_message.do", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
	@ResponseBody
	public String front_get_message(String jsoncallback, String id) {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			messageService.update_checkstatus(Integer.parseInt(id),1);
			map.put("flag",1);

		} catch (Exception e) {
			logger.error("获取消息失败", e);
			// TODO Auto-generated catch block
		}
		Gson gson = new Gson();
		String str = gson.toJson(map);
		return jsoncallback + "(" + str + ")";
	}
}
